package com.ymt.order.service.impl;

import com.ymt.common.tools.JsonWrapper;
import com.ymt.order.service.OrderCodeService;
import com.ymt.order.service.OrderService;
import com.ymt.producer.domain.Order;
import com.ymt.reliable.message.service.TransactionMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class AbstractOrderService implements OrderService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractOrderService.class);
    private static final String PAYORDERQUEUE = "PAYORDERQUEUE";

    @Autowired(required = false)
    private TransactionMessageService transactionMessageService;
    @Autowired
    private OrderCodeService orderCodeService;

    @Override
    public void payOrder(Order order) {
        order.setOrderCode(orderCodeService.createOrderCode());
        String messageBody = JsonWrapper.writeValue(order);
        String messageId = transactionMessageService.savePreparMessage(messageBody, PAYORDERQUEUE, order.getOrderCode(), null, null);
        LOGGER.info(">>> 预发送消息,消息编号:{}", messageId);

        boolean businessOk = false;
        try {
            Long orderId = addPayOrder(order);
            LOGGER.info(">>> 插入订单,订单编号:{}", orderId);
            businessOk = true;
        } catch (Exception e) {
            transactionMessageService.delete(messageId);
            LOGGER.info(">>> 业务执行异常删除消息,消息编号:{}", messageId, e);
        } finally {
            if (businessOk) {
                try {
                    transactionMessageService.confirmAndSend(messageId);
                    LOGGER.info(">>> 确认并且发送消息到实时消息中间件,消息编号:{}", messageId);
                } catch (Exception e) {
                    LOGGER.error(">>> 消息确认异常,消息编号:{}", messageId, e);
                }
            }
        }
    }

    protected abstract Long addPayOrder(Order order);
}
